import { formatDateOfYMD } from "../formatDate/index.js";

const ONE_MINUTE = 60 * 1000
const ONE_HOUR = 60 * ONE_MINUTE
const ONE_DAY = 24 * ONE_HOUR
const ONE_MONTH = 30 * ONE_DAY
const ONE_YEAR = 365 * ONE_DAY

// 获取过去多长时间
function getTimeAgo(timestamp) {
    if (isNaN(timestamp)) {
        return
    }
    const TIME = Date.now()
    let diff = TIME - timestamp
    let ago = ''
    switch (true) {
        case (diff < ONE_MINUTE):
            // 如果和当前时间少于一分钟
            ago = '刚刚'
            break;
        
        case (diff < (ONE_HOUR) && diff > (ONE_MINUTE)):
            // 如果小于一个小时，展示几分钟前
            ago = Math.floor(diff / 1000 / 60) + "分钟前"
            break;
            
        case (diff > (ONE_HOUR) && diff < (ONE_DAY)):
            // 如果大于等于一小时，小于一天，展示几小时前
            ago = Math.floor(diff / 1000 / 60 / 60) + "小时前"
            break;
            
        case (diff >= (ONE_DAY) && diff < (ONE_MONTH)):
            // 如果大于等于一天，小于30天，展示几天前
            ago = Math.floor(diff / 1000 / 60 / 60 / 24) + "天前"
            break;
            
        case (diff >= (ONE_MONTH) && diff < (ONE_YEAR)):
            // 如果大于30天，小于1年，展示几个月前
            ago = Math.floor(diff / 1000 / 60 / 60 / 24 / 30) + "个月前"
            break;
            
        case (diff >= (ONE_YEAR)):
            // 大于一年，展示时间
            ago = formatDateOfYMD(timestamp)
            break;
            
        default:
            // 默认展示时间
            ago = formatDateOfYMD(timestamp)
            break;
    }

    return ago
}

export {
    getTimeAgo
}